<template>
  <section class="f-order-sale">
    <div class="w-card my-content-box" v-if="!isDetail">
      <div class="title-box">
        <span class="title-text">佣金订单</span>
        <!-- <div style="margin-left:auto;">
          <el-button @click="setOrderIncomeDown()">导出</el-button>
        </div> -->
      </div>
      <div class="my-search-box">
        <div>
          <span>佣金订单：</span>
          <el-input v-model="searchForm.businessOrderId" clearable placeholder="请输入佣金订单" />
        </div>
        <div>
          <span>业务订单：</span>
          <el-input v-model="searchForm.incomeOrderId" clearable placeholder="请输入业务订单" />
        </div>
        <div>
          <span>代理商：</span>
          <el-select v-model="searchForm.shopId" clearable>
            <el-option v-for="item in shopList" :key="item.shopId" :label="item.shopName" :value="item.shopId" />
          </el-select>
        </div>
        <div>
          <span>佣金来源：</span>
          <el-select v-model="searchForm.incomeWay" clearable>
            <el-option label="直接" value="1" />
            <el-option label="间接" value="2" />
            <el-option label="团队" value="3" />
          </el-select>
        </div>
      </div>
      <div class="my-search-box">
        <div>
          <span>佣金类型：</span>
          <el-select v-model="searchForm.incomeType" clearable>
            <el-option v-for="item in incomeTypeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="datebox">
          <span>时间段：</span>
          <el-radio-group v-model="searchForm.timeType">
            <el-radio :label="1">分佣时间</el-radio>
            <el-radio :label="2">解冻时间</el-radio>
          </el-radio-group>
          <section style="width:380px;margin-left:10px">
            <el-date-picker v-model="searchForm.date" type="datetimerange" value-format="x" start-placeholder="开始时间"
              end-placeholder="结束时间" @change="(e) => {console.log(e)}" />
          </section>
        </div>
        <div class="f-ml-20">
          <el-button @click="searchHandle" type="primary">查询</el-button>
          <el-button @click="resetHandle">重置</el-button>
        </div>
      </div>

      <div class="my-table-box">
        <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
          :cell-style="{fontSize:'12px',color:'#7b7b7d'}" :data="tableData" stripe>
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column prop="orderId" label="佣金订单" width="200">
            <template v-slot="scope">
              {{ scope.row.incomeOrderId || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="uniqueName" label="代理商" align="center">
            <template v-slot="scope">
              {{ scope.row.uniqueName || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="incomeStr" label="佣金金额(元)" align="center">
            <template v-slot="scope">
              {{ scope.row.incomeStr || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="incomeName" label="佣金名称" align="center">
            <template v-slot="scope">
              {{ scope.row.incomeName || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="incomeName" label="佣金来源" align="center" width="80">
            <template v-slot="scope">
              {{ incomeWay[scope.row.incomeWay] || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="incomeState" label="佣金状态" align="center">
            <template v-slot="scope">
              {{ incomeState[scope.row.incomeState] || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="分佣时间" align="center">
            <template v-slot="scope">
              {{ getDateTime(scope.row.createTime)[6] || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="orderStatus" label="计划解冻时间" align="center">
            <template v-slot="scope">
              {{ getDateTime(scope.row.unfreezeTime)[6] || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="goodsName" label="关联商品" align="center">
            <template v-slot="scope">
              {{ scope.row.goodsName || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="incomeType" label="佣金类型" align="center">
            <template v-slot="scope">
              {{ incomeType[scope.row.incomeType] || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="businessOrderId" label="业务订单" width="200">
            <template v-slot="scope">
              <a class="f-link" @click="lookDetail(scope.row.businessOrderId)">
                {{ scope.row.businessOrderId || '' }}
              </a>
            </template>
          </el-table-column>
        </el-table>
        <div class="my-table-footer">
          <el-pagination style="margin-left:auto;" v-model:currentPage="page" v-model:page-size="size"
            :page-sizes="[10, 20, 50, 100]" small :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <!-- 导入弹窗 -->
    <Upload ref="uploadRef" v-if="off.upload" :uploadForm="uploadForm" @handleUploadSuccess="importSuccess"
      @handleUploadCancel="off.upload = false" />

    <router-view></router-view>
  </section>
</template>

<script>
import { onMounted, reactive, ref, toRefs, watch, nextTick } from 'vue'
import { getWindowWidthAndHeight, warningDeal, getDateTime, successDeal, BlobDownLoad } from '@/utils/utils'
import { useRoute, useRouter } from 'vue-router'
import Upload from '@/components/Upload.vue'
import api from '../api'

export default {
  components: { Upload },

  setup() {
    const route = useRoute()
    const router = useRouter()

    const uploadRef = ref(null)

    const state = reactive({
      off: {
        upload: false,
      },
      isDetail: false,

      searchForm: {
        "businessOrderId": "",
        "goodsId": "",
        "incomeOrderId": "",
        "incomeState": "",
        "incomeType": "",
        "incomeWay": "",
        "shopId": "",
        "unfreezeTimeEnd": "",
        "unfreezeTimeStart": "",
        "userId": ""
      },
      timeType: 1,
      searchFormDeep: {},

      tableHeight: 0,
      tableData: [],
      page: 1,
      size: 10,
      total: 0,

      incomeState: {
        '1': '冻结中',
        '2': '已解冻',
      },
      incomeWay: {
        '1': '直接',
        '2': '间接',
        '3': '团队',
      },

      incomeTypeList: [
        { label: '入账', value: '1' },
        { label: '核减', value: '2' },
      ],
      incomeType: {
        '1': '入账',
        '2': '核减',
      },

      goodsList: [],
      packageList: [],
      shopList: [],

      uploadForm: {
        dialogTitle: '导入加盟订单',
        action: '/eas/manage/order/join/upload'
      }
    })

    watch(() => route.path, (newVal, oldVal) => {
      setIsDetail()
    })

    function setIsDetail() {
      state.isDetail = (route.path != '/orderIncome')
      getTableData()
    }

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.searchForm = JSON.parse(JSON.stringify(state.searchFormDeep))
      searchHandle()
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
        createTimeStart: state.searchForm.date && state.searchForm.date[0],
        createTimeEnd: state.searchForm.date && state.searchForm.date[1],
        orderBy: 'id desc',
      }
      api.orderIncome(obj).then(res => {
        if (res.code == '200') {
          state.tableData = res.data.list
          state.total = res.data.total
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function lookDetail(sysOrderId) {
      router.push({ path: '/orderSale/detail', query: { sysOrderId } })
    }

    const getOrderJoinPackage = (goodsId) => {
      state.packageList = []
      state.searchForm.packageId = ''
      let json = {
        goodsId
      }
      api.orderJoinPackage(json).then(res => {
        state.packageList = res.data
      })
    }

    const setOrderIncomeDown = () => {
      const obj = {
        responseType: 'blob',
        ...state.searchForm,
        timeMin: state.searchForm.date && state.searchForm.date[0],
        timeMax: state.searchForm.date && state.searchForm.date[1],
        orderBy: 'id desc',
      }
      api.orderIncomeDown(obj).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log(err)
      })
    }

    //导入成功
    function importSuccess() {
      state.page = 1
      getTableData()
    }

    function importHandle() {
      state.off.upload = true
      nextTick(() => {
        uploadRef.value.off.dialog = true
      })
    }

    const getShopAll = () => {
      api.shopAll().then(res => {
        state.shopList = res.data
      })
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 330
      state.searchFormDeep = JSON.parse(JSON.stringify(state.searchForm))
      setIsDetail()
      getShopAll()
    })

    return {
      ...toRefs(state),
      uploadRef,
      searchHandle,
      resetHandle,
      lookDetail,
      handleCurrentChange,
      handleSizeChange,
      getDateTime,
      getOrderJoinPackage,
      setOrderIncomeDown,
      importSuccess,
      importHandle,
    }
  }
}
</script>

<style lang="scss" scoped>
.f-order-sale {
  .my-content-box {
    box-sizing: border-box;
    padding: 20px;

    > .title-box {
      display: flex;
      align-items: center;

      > .title-text {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .my-search-box {
      box-sizing: border-box;
      padding: 20px 20px 20px 0;
      padding-bottom: 0;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 10px;

      > div {
        width: 300px;
        display: flex;
        align-items: center;

        > span {
          flex-shrink: 0;
          width: 90px;
          text-align: right;
        }
      }

      .datebox {
        width: 720px;
      }
    }

    .my-table-box {
      margin-top: 20px;

      .table-handle-box {
        display: flex;
        justify-content: space-around;
        align-items: center;
      }

      .my-table-footer {
        display: flex;
        align-items: center;
        margin-top: 10px;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }
  .f-link {
    // text-decoration: underline;
    color: #409eff;
    cursor: pointer;
  }
}
</style>